package com.penjin.android.activity.apply;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.easemob.util.NetUtils;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.penjin.android.R;
import com.penjin.android.constants.HttpConstants;
import com.penjin.android.domain.PenjinBillMan;
import com.penjin.android.domain.PenjinCompany;
import com.penjin.android.domain.PenjinStaff;
import com.penjin.android.domain.PenjinUser;
import com.penjin.android.http.HttpConstant;
import com.penjin.android.http.HttpService;
import com.penjin.android.service.UserService;
import com.penjin.android.utils.BitmapUtils;
import com.penjin.android.utils.JsonUtils;
import com.penjin.android.utils.ToastHelper;
import com.penjin.android.view.CircleImageView;
import com.penjin.android.view.CustomProgressDialog;
import com.penjin.android.view.TitleBarView;
import com.penjin.android.view.penjin.FlowLine;
import com.penjin.android.view.penjin.FlowMan;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 单个申请单的明细界面
 * Created by maotiancai on 2016/1/20.
 */
public abstract class BillApplyDetailActivity extends FragmentActivity {

    CustomProgressDialog progressDialog;
    TitleBarView titleBarView;//标题栏
    TextView billNumber;//单据编号
    TextView billTypeName;//单据类型
    TextView type;//子种类

    TextView name;//用户公司真实姓名
    TextView department;//部门
    TextView zhiwu;//用户职务
    TextView passDay;//表单已经经过的天数

    TextView timeName;//申请单时间描述
    TextView timeDays;//申请总计时长
    TextView startTime;
    TextView endTime;
    TextView detail;
    TextView fujian;
    CircleImageView avatar;
    LinearLayout flowLineWrapper; //审批流程的父控件

    PenjinUser user;
    PenjinCompany company;
    PenjinStaff staff;

    HttpService httpService;
    TextHttpResponseHandler handler;
    TextHttpResponseHandler billProcessHandler;
    String billSort;
    String billDate;
    String billNum;
    int id;

    View buttonWrapper;
    boolean isDoneOrRefused = false;
    boolean isDetailInfoLoaded = false;
    boolean isWorkFlowLoaded = false;

    List<PenjinBillMan> dataList = new ArrayList<PenjinBillMan>();

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                refreshBillProcess();
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_activity_bill_detail);
        initData(savedInstanceState);
        initView();
        initHttp();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NetUtils.hasNetwork(this)) {
            if (!isDetailInfoLoaded) {
                if (user.isInCompany()) {
                    progressDialog.show();
                    loadBillType();
                }
            }
            if (!isWorkFlowLoaded) {
                loadBillProcess();
            }
        }
    }

    private void initView() {
        buttonWrapper = findViewById(R.id.buttonWrapper);
        if (isDoneOrRefused) {
            buttonWrapper.setVisibility(View.INVISIBLE);
        }
        progressDialog = CustomProgressDialog.createDialog(this);
        progressDialog.setMessage("请稍后");
        titleBarView = (TitleBarView) findViewById(R.id.titleBarView);
        avatar = (CircleImageView) findViewById(R.id.avatar);
        billNumber = (TextView) findViewById(R.id.billNumber);
        billTypeName = (TextView) findViewById(R.id.billTypeName);
        type = (TextView) findViewById(R.id.type);
        name = (TextView) findViewById(R.id.name);
        department = (TextView) findViewById(R.id.department);
        zhiwu = (TextView) findViewById(R.id.zhiwu);
        passDay = (TextView) findViewById(R.id.passDay);
        timeName = (TextView) findViewById(R.id.timeName);
        timeDays = (TextView) findViewById(R.id.timeDays);
        startTime = (TextView) findViewById(R.id.startTime);
        endTime = (TextView) findViewById(R.id.endTime);
        detail = (TextView) findViewById(R.id.detail);
        fujian = (TextView) findViewById(R.id.fujian);
        flowLineWrapper = (LinearLayout) findViewById(R.id.flowLineWrapper);

        //加载个人信息
        BitmapUtils.loadUrlImage(user.getTouxiang(), avatar, this, false);//显示头像
        department.setText(JsonUtils.isJsonNull(staff.getDepartment()) ? "暂未分配部分" : staff.getDepartment());
        zhiwu.setText(JsonUtils.isJsonNull(staff.getPosition()) ? "" : staff.getPosition());
        name.setText(JsonUtils.isJsonNull(staff.getRealName()) ? user.getUsername() : staff.getRealName());
        onInitView();
    }

    protected abstract void onInitView();

    private void initData(Bundle savedInstanceState) {
        UserService userService = UserService.getInstance(this);
        user = userService.getCurrentUser();
        company = userService.getCurrentCompany();
        staff = userService.getCurrentStaff();
        Intent intent = getIntent();
        if (intent != null) {
            Bundle hodler = intent.getExtras();
            if (hodler != null) {
                billSort = hodler.getString("BillSort");
                billDate = hodler.getString("Date");
                id = hodler.getInt("Id");
                billNum = hodler.getString("BillNumber");
            }
            isDoneOrRefused = intent.getBooleanExtra("isDoneOrRefused", false);
        }
        if (billSort == null) {
            billSort = savedInstanceState.getString("BillSort");
            billDate = savedInstanceState.getString("Date");
            id = savedInstanceState.getInt("Id");
            billNum = savedInstanceState.getString("BillNumber");
            isDoneOrRefused = savedInstanceState.getBoolean("isDoneOrRefused", false);
        }
        onInitData(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("BillSort", billSort);
        outState.putString("Date", billDate);
        outState.putInt("Id", id);
        outState.putString("BillNumber", billNum);
        outState.putBoolean("isDoneOrRefused", isDoneOrRefused);
    }

    protected abstract void onInitData(Bundle bundle);

    private void initHttp() {
        httpService = HttpService.getInstance(this);
        handler = new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                progressDialog.dismiss();
                if (s == null) {
                    s = "连接超时，请重试!";
                }
                onLoadBillDetailError(s);
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                System.out.println(s);
                progressDialog.dismiss();
                onLoadBillDetailSuccess(s);
            }
        };
        billProcessHandler = new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                progressDialog.dismiss();
                ToastHelper.showServerError(getApplicationContext());
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                progressDialog.dismiss();
                System.out.println(s);
                try {
                    JSONObject jo = new JSONObject(s);
                    boolean result = jo.optBoolean("result");
                    if (result) {
                        JSONArray datas = jo.getJSONArray("auditstep");
                        if (datas.length() > 0) {
                            dataList.clear();
                            for (int j = 0; j < datas.length(); j++) {
                                PenjinBillMan penjinBillMan = new PenjinBillMan();
                                JSONObject data = datas.getJSONObject(j);
                                penjinBillMan.name = data.getString("name");
                                penjinBillMan.phone = data.getString("phone");
                                penjinBillMan.flag = data.getBoolean("auditTag");
                                dataList.add(penjinBillMan);
                            }
                            mHandler.sendEmptyMessage(1);
                        }
                    }
                } catch (Exception e) {
                    ToastHelper.showJsonError(getApplicationContext());
                }
            }
        };
    }

    protected void loadBillType() {
        RequestParams params = generateParams();
        try {
            this.httpService.postRequest(this.getApplicationContext(), HttpConstants.HOST + HttpConstants.SpecificDetail, params, handler);
        } catch (Exception e) {
            e.printStackTrace();
            progressDialog.dismiss();
            ToastHelper.showDNSError(this);
        }
    }

    protected void loadBillProcess() {
        RequestParams requestParams = new RequestParams();
        requestParams.put("staffNumber", staff.getStaffNumber());
        requestParams.put("companyId", company.getCompanyId());
        requestParams.put("billSort", billSort);
        requestParams.put("date", billDate);
        requestParams.put("billNumber", billNum);
        try {
            httpService.postRequest(this, HttpConstants.HOST + HttpConstants.AuditProcedure, requestParams, billProcessHandler);
        } catch (Exception e) {
            e.printStackTrace();
            ToastHelper.showMessage("审批流过程请求错误", getApplicationContext());
        }
    }

    /**
     * 刷新该单据的审批流过程详情
     */
    protected void refreshBillProcess() {
        synchronized (this) {
            if (!isWorkFlowLoaded) {
                int count = flowLineWrapper.getChildCount();
                flowLineWrapper.removeViewAt(count - 1);
                PenjinBillMan billMan;
                for (int i = 0; i < dataList.size(); i++) {
                    billMan = dataList.get(i);
                    FlowMan flowMan = new FlowMan(this, billMan.flag);
                    flowMan.setTag(billMan);
                    flowMan.setName(billMan.phone);
                    flowMan.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ToastHelper.showMessage(((PenjinBillMan) v.getTag()).phone, getApplicationContext());
                        }
                    });
                    FlowLine flowLine = new FlowLine(this);
                    flowLineWrapper.addView(flowMan, -1);
                    flowLineWrapper.addView(flowLine, -1);
                }
                FlowMan doneTag = new FlowMan(this);
                doneTag.setName("完成");
                flowLineWrapper.addView(doneTag, -1);
                isWorkFlowLoaded = true;
            }
        }

    }

    /**
     * 更具单据类型，生成不同的请求参数
     *
     * @return
     */
    protected abstract RequestParams generateParams();

    /**
     * 加载订单详情成功的回调
     *
     * @param s
     */
    protected abstract void onLoadBillDetailSuccess(String s);

    /**
     * 加载订单详情失败的回调
     *
     * @param s
     */
    protected void onLoadBillDetailError(String s) {

        progressDialog.dismiss();
        ToastHelper.showMessage(s, this);

    }
}
